<?php

class NewsLetter_db
{
    /**
     *
     * @return <array user>
     */
    public function showAllUser(){
        try{
            require_once "models/Db/Db_Db.php";

            $db=Db_Db::conn();
            $statement="SELECT name,surname,preferiti,mail FROM newletter";
            $userList=$db->fetchAll($statement);
            $db->closeConnection();

        } catch(Zend_Db_Exception $e) {
            echo $e->getMessage();
        }
        return $userList;
    }

    /**
     *
     * @param <string> $mail
     * @return <type>
     */
    public function getUser($mail)
    {

        try{
            require_once "models/Db/Db_Db.php";

            $db=Db_Db::conn();
            $statement="SELECT name,surname,preferiti,mail FROM newletter WHERE mail='" .$mail. "'";
            $row=$db->fetchRow($statement);
            if (!$row) {
            throw new Exception("Could not find row $mail");
              }
            $db->closeConnection();

        } catch(Zend_Db_Exception $e) {
            echo $e->getMessage();
        }
        return $row;
     }

    /**
     *
     * @param <string> $name
     * @param <string> $surname
     * @param <string> $mail
     * @param <string> $preferiti
     * @return string
     */
    public function addUser($name,$surname, $mail, $preferiti)
    {
        require_once "models/Db/Db_Db.php";
        try{
            $db=Db_Db::conn();
            $table = 'newletter';
            $data = array(
                'name' => $name,
                'surname' => $surname,
                'mail' => $mail,
                'preferiti' => $preferiti,
                );
            $db->insert($table, $data);
        }catch(Zend_Db_Exception $e) {
            /*
             * ricorda di mettere insieme gli errori dei db.
             */
            $e->getMessage();
            $success="<p>C'&egrave; stato un errore durante l'inserimento nel nostro database. Se non sei già iscritto riprova pi&ugrave; tardi.</p>";
            }
        if (!isset($success)){
                $success="<p>Complimenti, sei ora iscritto alla newsletter di WhichClub!</p>";
        }
            return $success;
    }

    /**
     *
     * @param <string> $mail
     * @return string
     */
    public function deleteUser($mail)
    {
     try{
            require_once "models/Db/Db_Db.php";
            
            $table='newletter';
            $condition[]="mail=" ."'". $mail . "'";
            //echo $condition[];
            $db=Db_Db::conn();
            $a=$db->delete($table,$condition);
            if ($a==0){
                $success="Non &egrave; stato possibile eliminare questo indirizzo dal database.";
            } else {
                $success="Eliminazione avvenuta con successo.";
                }
            $db->closeConnection();

        } catch(Zend_Db_Exception $e) {
            /*
             * ricorda di mettere insieme gli errori dei db.
             */
            $e->getMessage();
        }
        return $success;
    }

    /**
     *
     * @return <array disco>
     */
    public function getDisco(){
        try{
            require_once "models/Db/Db_Db.php";

            $db=Db_Db::conn();
            $statement="SELECT * FROM disco";
            $discoList=$db->fetchAll($statement);
            $db->closeConnection();

        } catch(Zend_Db_Exception $e) {
            echo $e->getMessage();
        }
        return $discoList;
    }


    /**
     * in base alla p.iva prevelo gli
     * eventi di ogni discoteca
     *
     * @param <string> $piva
     * @return string
     */
    public function getEventByPiva($piva){
        try{
            require_once "models/Db/Db_Db.php";

            $db=Db_Db::conn();
            //get only active events
            $status=1;
            $statement="SELECT id,titolo,descrizione,data_inizio FROM edisco WHERE piva='"
                        . $piva . "' AND status='" . $status . "'";
            $event=$db->fetchAll($statement);

            $db->closeConnection();
            $eve="";
            foreach ($event as $event2){
                //print_r($event2['id']);
                $eve .="<hr><h3>" . $event2['titolo'] . "</h3>"
                        . "<h5><i>" . $event2['data_inizio'] . "</i></h5>"
                        . "<p>" . $event2['descrizione'] . "</p>"
                        . "<a href='http://localhost:10088/index/show-detail-event/id/0_" . $event2['id'] . "'>VEDI</a>"
                        . "<hr>";
                }
            //var_dump($event);
        } catch(Zend_Db_Exception $e) {
            echo $e->getMessage();
        }
        return $eve;
    }

    /**
     *
     * create an array of piva selected by the user
     * from newletter db.
     *
     * @param <string> $preferiti
     * @return <string>
     */
    public function splitPiva($preferiti){

        $preferiti=substr($preferiti, 1);
        $pivaList = explode(":", $preferiti);

        return $pivaList;
    }

    /**
     *
     * return a var with the correct html
     * containing every event for each disco
     * which the user is subscribed
     *
     * @param <string> $pivaList
     * @return <array event>
     */
    public function getAllEventByPivaList($pivaList){
        $events = '';
        foreach ($pivaList as $pivaList2){
            $events .= $this->getEventByPiva($pivaList2);
        }
        //print_r($events);
        return $events;
    }

    /**
     *
     * Send newsLetter to one user.
     *
     * @param <string> $mail
     * @param <string> $eventMail
     * @param <date> $date
     */
    public function sendNewsLetter($mail, $eventMail, $date){

            // configuro l'host da cui mando l'email
            $configInfo = array('auth'=>'login','ssl' => 'tls', 'username'=>'whichclub@gmail.com','password'=>'prosegui');
            $smtpHost = new Zend_Mail_Transport_Smtp('smtp.gmail.com',$configInfo);

            // preparo il corpo della mail
            $emailheader="<h2>Gli eventi della settimana!</h2>";
            $emailbody=$eventMail;
            $emailfooter="<br /><h6>Per non ricevere pi&ugrave;"
                            . " NewsLetter premi <a href='http://www.whichclub.it'>qui</a>"
                            . " e vai nella sezione NewsLetter."
                            . " Per qualsiasi informazione: info@whichlcub.it<br />"
                            . "All rigth reserved @whichclub.it - Booking Events</h6>";
            $emailMessage=$emailheader . $emailbody . $emailfooter;

            $fromEmail="whichclub@gmail.com";
            $fromFullName="WhichClub.it - NewsLetter";
            $to=$mail;

            //$bcc="falanga.fra@gmail.com";
            $subject="Eventi della settimana - " . $date;

            $MailObj = new Zend_Mail();
            $MailObj->setBodyHtml($emailMessage);
            $MailObj->setFrom($fromEmail,$fromFullName);
            $MailObj->addTo($to);
            //$MailObj->addBcc($bcc);
            $MailObj->setSubject($subject);

            try{
                $MailObj->send($smtpHost);
                //$MailObj->send();
                $message=true;

            } catch (Zend_Mail_Exception $e){
                echo $e->getMessage();
                //error messagge
            }

        }


    /**
     *
     * Send newsLetter to all users.
     *
     */
    public function creacteMailNewsLetter(){
        
        $today = getdate();
        $date = $today['weekday'] . " " .  $today['month'] . " " . $today['year'];

        $userList = $this->showAllUser();

        /*
         * per ogni utente prendo i preferiti e le pive poi stampo events.
         * foreach ($userList as $userList2){]
         */
        foreach ($userList as $user) {
            $mail=$user['mail'];
            $preferiti=$user['preferiti'];
            $pivaList=$this->splitPiva($preferiti);
            $eventMail=$this->getAllEventByPivaList($pivaList);
            //$this->sendNewsLetter($mail, $eventMail,$date);
        }
    }

    /**
     *
     * save the contact of an user in db
     *
     * @param <array string> $info
     */
    public function saveContactInfo($info){
            try {
                require_once "models/Db/Db_Db.php";

                $db = Db_Db::conn();
                $db->insert('informazioni', $info);

                // i close the connection
                $db->closeConnection();
            } catch (Zend_Db_Exception $e) {
                echo $e->getMessage();
            }
    }

    /**
     *
     * @param <string> $data
     */
    public function saveSerata($data){
            try {
                require_once "models/Db/Db_Db.php";

                $db = Db_Db::conn();
                $db->insert('organizza_serata', $data);

                // i close the connection
                $db->closeConnection();
            } catch (Zend_Db_Exception $e) {
                echo $e->getMessage();
            }
    }

}